package cn.ybz21.hibot.resource.sim;

import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cn.ybz21.hibot.bean.ResultCode;
import cn.ybz21.hibot.bean.data.Location;
import cn.ybz21.hibot.util.StaticValues;
import ros.Publisher;
import ros.RosBridge;
import ros.msgs.std_msgs.PrimitiveMsg;

@Path("/sim")
public class SimulationResource {
	/**
	 * http://127.0.0.1:8080/HiBotServer/api/v1/sim
	 * 
	 * 
	 * @return
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Location getDefaultLocation() {

		if (!CollisionCheck.getInstance().isFlag())
			new Thread() {
				@Override
				public void run() {
					CollisionCheck.getInstance().start();
				}
			}.start();
		return new Location();
	}

	@POST
	@Path("/uploadSim")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode uploadSim(@FormParam("data") String data) {
		System.out.println(data);
		List<UavData> list = new Gson().fromJson(data, new TypeToken<List<UavData>>() {
		}.getType());
		SimulationData.uavList = list;
		return new ResultCode(1);
	}

	/**
	 * http://127.0.0.1:8080/HiBotServer/api/v1/sim/publish/1,1,3
	 * 
	 * @param str
	 * @return
	 */
	@GET
	@Path("/publish/{str}")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode publish(@PathParam("str") String str) {
//		if (!CollisionCheck.getInstance().isFlag())
//			CollisionCheck.getInstance().start();
		System.out.println(str);
		String url = StaticValues.URL_SIM;
		// String url="ws://192.168.0.121:9090";
		RosBridge bridge = ROSMessageCenter.getBridge(url);
		Publisher pub = new Publisher("/uav_control", "std_msgs/String", bridge);
		pub.publish(new PrimitiveMsg<String>(str));

		SimulationData.cmdMap.put(str.split(",")[0], str);

		return new ResultCode(1);
	}
}
